package com.risen.project.common;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 统一返回值
 *
 * @param <T>
 */
@Data
public class Response<T> implements Serializable {
    /**
     * 状态码
     */
    private String code;
    /**
     * 状态信息
     */
    private String msg;
    /**
     * 返回值
     */
    private T data;
    /**
     * 当前时间戳
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime timestamp;

    /**
     * 总条数
     */
    private Long total;

    public Response(String code, String msg, T data, LocalDateTime timestamp, long total) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.timestamp = timestamp;
        this.total = total;
    }

    public static <T> Response<T> success() {
        return createResponse(ResponseStatusCode.SUCCESS.getCode(), ResponseStatusCode.SUCCESS.getMsg(), null, 0);
    }

    public static <T> Response<T> success(T data) {
        return createResponse(ResponseStatusCode.SUCCESS.getCode(), ResponseStatusCode.SUCCESS.getMsg(), data, 0);
    }

    public static <T> Response<T> success(T data, long total) {
        return createResponse(ResponseStatusCode.SUCCESS.getCode(), ResponseStatusCode.SUCCESS.getMsg(), data, total);
    }

    public static <T> Response<T> fail(ResponseStatusCode responseStatusCode) {
        return createResponse(responseStatusCode.getCode(), responseStatusCode.getMsg(), null, 0);
    }

    public static <T> Response<T> fail(String code, String msg) {
        return createResponse(code, msg, null, 0);
    }

    private static <T> Response<T> createResponse(String code, String msg, T data, long total) {
        return new Response<>(code, msg, data, LocalDateTime.now(), total);
    }
}
